﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Kotonoha.Objects;
using Kotonoha.Objects.SuperMemo;
using Kotonoha.Server.Db.Dao;
using Kotonoha.Server.Objects.Model;
using Kotonoha.Server.Core.Utils;
using Kotonoha.Server.Model;
using Kotonoha.Server.Settings;
using Kotonoha.Server.Synch;

namespace Kotonoha.Server.UI.Synch {
    /// <summary>
    /// Interaction logic for SynchForm.xaml
    /// </summary>
    public partial class SynchForm : Window {
        public SynchForm() {
            InitializeComponent();

            Setting s = SettingsManager.Acquire("synch");
            object o = s["items-num"];
            if (o == null) {
                s["items-num"] = 50;
            }
        }

        public WordHolder Words { get; set; }

        private void SynchBtn_Click(object sender, RoutedEventArgs e) {
            Synchronizer synch = new Synchronizer(Words);
            synch.ContainerFnc = MakeContainer;
            Status.Text = synch.synchronize() ? "OK" : "Failed";
        }

        private Container MakeContainer() {
            Container c = new Container();
            
            Setting s = SettingsManager.Acquire("synch");
            HashSet<string> chs = new HashSet<string>();

            Random r = new Random();

            int count = (int)(s["items-num"] ?? 50);

            var e = Words.Collection
                .Where(word => word.LearningData != null)
                .Where(word => word.LearningData.IntervalEnd < DateTime.Now)
                .OrderBy(word => word.LearningData.IntervalEnd)
                .Take(count).ToList();
            c.Words.AddRange(e);
            chs.UnionWith(e.SelectMany(w => KanjiFactory.enumerateKanji(w.Writing)));
            count -= c.Words.Count;

            if (count > 0) {
                /*var candidates = Words.Collection.Where(w => w.LearningData == null).ToList();
                while (count > 0) {
                    var selected = candidates[r.Next(candidates.Count)];
                    if (!c.Words.Contains(selected)) {
                        c.Words.Add(selected);
                        --count;
                        chs.UnionWith(KanjiFactory.enumerateKanji(selected.Writing));
                    }
                }*/
                var candidates = Words.Collection
                    .Where(w => w.LearningData == null)
                    .OrderBy(w => w.AddedDate)
                    .Take(count).ToList();
                chs.UnionWith(candidates.Select(w => w.Writing).SelectMany(wr => KanjiFactory.enumerateKanji(wr)));
                c.Words.AddRange(candidates);
            }
            c.Kanji = new ModelDao(HibernateUtil.Model.Session).findAllKanji(chs);
            c.Matrix = OFMatrixHolder.Matrix.Dump();
            return c;
        }
    }
}
